/*
 *   AS IS License
 * ==Naive Coders==
 */
package org.naive.metawatch.converter.parser;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.text.ParseException;

/**
 *
 * @author gbu.000
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ParsedFixedSizeArray {

    int length();

    Class<? extends Parseable> itemClass();

    public class FieldParser {

        public static Object parse(ParsedFixedSizeArray p, ParseContext x, Field f)
                throws ParseException, InstantiationException, IllegalAccessException {
            Class<?> componentType = f.getType().getComponentType();
            return parse(x, p.length(), p.itemClass(), componentType);
        }

        public static Object parse(ParseContext px,
                int length,
                Class<? extends Parseable> itemClass,
                Class<?> componentType)
                throws ParseException, InstantiationException, IllegalAccessException {
            final Object array = Array.newInstance(componentType, length);
            for (int i = 0; i < length; i++) {
                final Parseable item = itemClass.newInstance();
                item.parse(px);
                Array.set(array, i, item);
            }
            return array;
        }
    }
}
